from datetime import datetime
from quart import Quart
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import Session
from config import DB


def initDB(app: Quart) -> None:
    """
    生成数据库 engine
    """
    app.db = get_connection()


def get_connection() -> scoped_session:
    """
    生成数据库连接
    todo 优化 mysql 链接
    """
    url = f"{DB['protocol']}://{DB['user']}:{DB['password']}@{DB['addr']}:{DB['port']}/{DB['dbname']}?charset={DB['charset']}"
    engine = create_engine(url, max_overflow=10, pool_size=20, pool_timeout=60)
    session_factory = sessionmaker(bind=engine)
    return scoped_session(session_factory)


def _to_dict(self, safe=True):
    """
    to dict
    """
    d = {}
    for c in self.__table__.columns:
        if (not safe) or (c.name not in self._hidden_not_safe):
            val = getattr(self, c.name, None)
            # None 值处理
            if val is None:
                val = ''

            # 处理 datetime 格式化
            if isinstance(val, datetime):
                val = val.strftime("%Y-%m-%d %H:%M:%S")

            d.update({
                c.name: val
            })

    return d


# Model 基类
Base = declarative_base()
# do not show when convert it to dict
Base._hidden_not_safe = []
Base.to_dict = _to_dict
